//1. 引入axios
import axios from "axios";

//引入store
import store from "../store"

//引入element-ui的loading组件
import { Loading } from 'element-ui';

//创建loading
let loading = {
    //保存的Loading.service的实例化对象
    loadingInstance : null,
    //打开loading方法
    open : function(){
      if(this.loadingInstance == null){
        this.loadingInstance =  Loading.service({
            target : ".main",
            background : "rgba(0, 0, 0, 0.7)",
            text: '加载中...',
            spinner: 'el-icon-loading',
        });
      }  
    },
    //关闭loading 方法
    close : function(){
      if(this.loadingInstance !== null){
        this.loadingInstance.close()
      }  
      this.loadingInstance = null;
    }
}

//2. 创建axios实例对象
const request = axios.create({
    //配置请求的公共接口地址
    baseURL: process.env.VUE_APP_BASE_API,
    //配置请求的超时时间
    timeout: 5000
})

//3. 创建请求拦截器
request.interceptors.request.use(function (config) {
    //获取vuex里面保存的token
    let token = store.state.token;
    //通过请求头将token发送给后台
    config.headers.token = token;
    //开启loading
    loading.open()

    return config;
}, function (error) {
    //关闭loading
    loading.close()
    return Promise.reject(error);
});

//4. 创建响应拦截器
request.interceptors.response.use(function (response) {
    //关闭loading
    loading.close()
    return response;
}, function (error) {
    //关闭loading
    loading.close()
    return Promise.reject(error);
});


//5. 导出axios实例对象
export default request










